package cn.com.callback


import cn.com.elite.EliteBean
import net.sf.json.JSONArray
import org.springframework.jdbc.core.JdbcTemplate;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import cn.com.elite.Util;
import net.sf.json.JSONObject;
import cn.com.kh.KHUtil;

/**
 *
 * @author xrm
 * @use 查询收费项列表
 *
 *
 */
public class apiGetFeeitemList implements ServiceBackInvoke{
    private static final Log log=LogFactory.getLog(apiGetFeeitemList.class);
    private String charset = "utf-8"; //设置字符集
    private int timeout = 100000; //设置请求超时时间
    private int enableSSLflag = 1;
    public String doCallBack(EliteBean eliteBean, HttpServletRequest request,HttpServletResponse response){
        response.setCharacterEncoding("UTF-8");
        response.setContentType("application/json");
        JSONObject result = new JSONObject();
        def smap,oJson,SaveResult;
        try {
            //获取客户端传参
            def r_params = Util.filterForObject(request.getParameter("params")); //获取json字符串
            log.debug("NGS传参:"+r_params+" | ");
            //传参处理

            //列表接口调用
            /*
            if(r_params.equals("")) {
                result.put("code", "-1");
                result.put("msg", "未传递参数！");
                return result
            }*/

            oJson = CustHttpPort(eliteBean); //调用接口方法

            log.debug("接口返回:"+oJson);
            return	oJson;


        }catch (Exception e) {
            log.error("errormsg:", e)
            result.put("code", "-1");
            result.put("msg", "调用失败！");
            return result;
        }
    }


/**
 *
 * @use 收费项信息保存
 * @param eliteBean
 * @param
 * @return
 */
    private String CustHttpPort(EliteBean eliteBean) {
        JdbcTemplate jt = new JdbcTemplate(eliteBean.getDataSource());

        JSONObject result = new JSONObject();
        def smap,mopsmap,chatqueue,customer_guid,url="";
        try {
            //获取接口地址
            smap = eliteBean.chaxun_sql("select target_url as url from sys_interface_config where type ='getFeeitemList'","dataSource");
            if(smap.size()==0) {
                result.put("msg", "找不到对应接口");
                result.put("code", "-1");
                return result;
            }else{
                url = smap[0].getAt("url");
            };



            def postmap=Util.doHttpPost(url,'',charset,timeout,enableSSLflag);
            log.debug("接口返回:"+postmap);
            JSONObject obj = JSONObject.fromObject(postmap);
            if(obj.getInt("status")!=200) {
                result.put("code","-1");
                result.put("msg", "接口调用异常");
                return result;
            }else{
                JSONArray fee_list=obj.getJSONArray("data");
                for(def i=0;i<fee_list.size();i++){
                    JSONObject feeJSON=JSONObject.fromObject(fee_list.get(i));
                    String csqls="select count(1) nums from fee_type where id='"+feeJSON.getString("feeitemid")+"'";
                    def csqlsnum=eliteBean.chaxun_sql(csqls,"dataSource");
                    if(csqlsnum[0].get("nums")==0) {
                        List<Object> valueList = new ArrayList<Object>();
                        valueList.add(feeJSON.getString("feeitemid"));
                        valueList.add(feeJSON.getString("feeitemname"));
                        valueList.add(feeJSON.getString("feeitemoid"));
                        String sqls = "insert into fee_type(fee_guid,id,feedesc,feeoid) values(uuid(),?,?,?)";

                        int tabcResule = jt.update(sqls, valueList.toArray());
                    }else{
                        List<Object> valueList = new ArrayList<Object>();
                        valueList.add(feeJSON.getString("feeitemname"));
                        valueList.add(feeJSON.getString("feeitemoid"));
                        valueList.add(feeJSON.getString("feeitemid"));
                        String sqls = "update fee_type set feedesc=?,feeoid=? where id=?";

                        int tabcResule = jt.update(sqls, valueList.toArray());

                    }

                }

                return obj;
            };

        }catch (Exception e) {
            log.error("errormsg:", e)
            result.put("code", "-1");
            result.put("msg", "程序异常");
            return result;
        }
    }





    public String ASCIIORDER(Map<String, String> map) {
        JSONObject result = new JSONObject();
        // 对所有传入参数按照字段名的 ASCII 码从小到大排序
        List<Map.Entry<String, String>> infoIds = new ArrayList<Map.Entry<String, String>>(map.entrySet());
        Collections.sort(infoIds, new Comparator<Map.Entry<String, String>>() {
            public int compare(Map.Entry<String, String> A, Map.Entry<String, String> B) {
                return (A.getKey()).toString().compareTo(B.getKey());
            }
        });

        // 构造签名键值的格式
        StringBuilder stringsign = new StringBuilder();
        StringBuilder sign = new StringBuilder();
        for (Map.Entry<String, String> item : infoIds) {
            if (item.getKey() != null || item.getKey() != "") {
                String key = item.getKey();
                String val = item.getValue();
                if (!(val == "" || val == null)) {
                    sign.append(key + "=" + URLEncoder.encode(val, "UTF-8") + "&");
                }
                if (!(val == "" || val == null)&&!(key == "key")) {
                    stringsign.append(key + "=" + val + "&");
                }
            }
        }
        String md5sign = Util.getMD5Str(sign.substring(0, sign.length()-1));
        return stringsign.append("sign="+md5sign);
    }
}








